package com.xxxx.mail;

import com.rabbitmq.client.Channel;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * 消息接收者，因为我们在yeb-server子项目的EmployeeServiceImpl类中，添加员工时发送了消息，所以在这里是接收消息
 * Created by HMF on 2021/08/16 23:12
 */
@Component
public class MailReceiver {

    // 准备日志打印，使用slf4j日志打印，门面模式
    private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

    // 下面三个都是跟邮件相关的东西
    @Autowired
    private JavaMailSender javaMailSender;  // 注入邮件发送对象
    @Autowired
    private MailProperties mailProperties;  // 邮件的属性配置，在application.yml中
    @Autowired
    private TemplateEngine templateEngine; // thymeleaf模板引擎
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 因为使用了 rabbitTemplate.convertAndSend("mail.welcome", emp); 发送消息
     * 所以在这里就要监听他的RoutingKey: mail.welcome
     *
     * @param message
     */
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME) // 改为定义的常量
    public void handler(Message message, Channel channel) {
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        // 消息序号
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 里面的参数是固定的
        String msgId = (String) headers.get("spring_returned_message_correlation");
        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            if (hashOperations.entries("mail_log").containsKey(msgId)) {
                LOGGER.error("消息已经被消费============>{}", msgId);
                /**
                 * 手动确认消息
                 * tag：消息序号
                 * multiple：是否确认多条
                 */
                channel.basicAck(tag, false);
                return;
            }

            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);

            // 发件人
            helper.setFrom(mailProperties.getUsername());  // 获取在application.yml中配置邮件的的信息
            // 收件人
            helper.setTo(employee.getEmail());
            // 邮件主题
            helper.setSubject("入职欢迎邮件");
            // 发送日期
            helper.setSentDate(new Date());

            // 邮件内容
            Context context = new Context(); // thymeleaf 的Context
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());


            String mail = templateEngine.process("mail", context); // 这里的mail要与mail.html对应
            // 设置邮件的发送模板
            helper.setText(mail, true); // 这里要加上true,不然显示的是html的源码

            // 发送邮件
            javaMailSender.send(msg);

            LOGGER.info("邮件发送成功！");
            // 将消息id存入redis
            hashOperations.put("mail_log", msgId, "OK");
            // 手动确认消息
            channel.basicAck(tag, false);

        } catch (Exception e) {
            /**
             * 手动确认消息
             * tag：消息序号
             * multiple：是否确认多条
             * requeue：是否要退回到队列
             */
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            LOGGER.error("邮件发送失败=======>{}", e.getMessage());
        }
    }

}

